﻿using System;
using System.Runtime.Serialization;

namespace SoftwareLogistics.SharepointClient.Models
{
    public class ContentBase
    {
        public static void SaveToIsolatedStorage<T>(string fileName, T contents) where T : class
        {
            var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

            using (var file = store.CreateFile(string.Format("{0}.dat", fileName)))
            {
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(file, contents);
            }
        }

        public static T ReadFromIsolatedStorage<T>(string listName) where T : class
        {
            var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            string fileName = string.Format("{0}.dat", listName);
            if (!store.FileExists(fileName))
                return null;

            using (var file = store.OpenFile(fileName, System.IO.FileMode.Open))
            {
                if (file != null)
                {
                    var serializer = new DataContractSerializer(typeof(T));
                    return serializer.ReadObject(file) as T;
                }
            }

            return null;
        }
    }
}